const Controller = require('egg').Controller
const path = require('path');
const fs = require('fs');
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const sd = require('silly-datetime');

class addNoteController extends Controller {
    async index() {
        const { ctx } = this

        await ctx.render('addNote.html',{
            message: ''
        })
    }

    async addNote(){
        const{ctx}=this
        const stream = await ctx.getFileStream();
        const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
        const target = path.join(this.config.baseDir, 'app/public/uploads', filename);
        const writeStream = fs.createWriteStream(target);
        try {
            //异步把文件流 写入
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            throw err;
        }

        let updatetimes = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        let url='/public/uploads/' + filename
        let data=stream.fields
        let id=ctx.session.uid
        data.id=id.ID
        data.url=url
        data.time=updatetimes

        let getFind=await ctx.service.addNote.find(data)

        if(!getFind){
            let getResult=await ctx.service.addNote.addResult(data)
            if(!getResult){
                await ctx.render('addNote.html',{
                    message: '添加文章失败'
                })
            }else{
                ctx.redirect('/')
            }
        }else{
            await ctx.render('addNote.html',{
                message: '标题重复'
            })
        }
    }
}

module.exports = addNoteController